package com.briup.srms.sms.web.controller;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import com.briup.srms.sms.bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.briup.srms.sms.bean.extend.StudentExtend;
import com.briup.srms.sms.service.IStudentService;
import com.jacky.base.utils.ExcelUtils;
import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.jacky.base.utils.PageVM;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: sms
 * @description: 实训学生控制器类
 * @author: jacky
 * @create: 2020-12-15 14:41
 **/
@Api(description="实训学生相关接口")
@Validated
@RestController
@RequestMapping("/studentTrain")
public class StudentTrainController {
	
	@Autowired
	private IStudentService studentService;
	
	@ApiOperation(value = "分页多条件获取学生信息")
	@GetMapping("pageQuery")
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"),
		@ApiImplicitParam(name = "realname", value = "姓名", paramType = "query"),
		@ApiImplicitParam(name = "trainId", value = "实训编号", paramType = "query"),
		@ApiImplicitParam(name = "channelId", value = "渠道编号", paramType = "query"),
	})
	public Message pageQuery(@NotNull int page,@NotNull  int pageSize,String realname,Long trainId,Long channelId) {
		PageVM<StudentExtend> pageVM = studentService.pageQuery(page, pageSize, realname, trainId, channelId);
		return MessageUtil.success(pageVM);
	}
	
	@ApiOperation(value = "下载模板", produces = "application/octet-stream")
	@GetMapping("downloadTemplate")
	public void downloadTemplate(HttpServletResponse response) throws Exception {
		// 2. 将excel导出
		// 2.1 excel头部数据
		String[] headList = new String[] {"学号", "姓名", "性别","手机号" };
		// 2.2 属性
		String[] fieldList = new String[] { "schoolStuNo","realname", "gender","tel" };
		// 2.3 数据列，需要转化
		List<Map<String, Object>> dataList = new ArrayList<>();
		// 2.4 导出文件名
		String excelName = "student_template";
		// 3. 调用工具方法导出Excel
		ExcelUtils.createExcel(response, excelName, headList, fieldList, dataList);
	}
	
	@ApiOperation(value = "文件上传", notes = "")
	@PostMapping("upload")
	public Message upload(@RequestParam("file") MultipartFile file, HttpServletRequest req,
			@NotNull Long channelId,@NotNull Long trainId,@NotNull Long graduationTime,@NotNull String education) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<Student> students = new ArrayList<>();
		for (List<Object> props : list) {
			Student student = new Student();
			// 设置渠道
			student.setChannelId(channelId);
			student.setGraduationTime(graduationTime);
			student.setEducation(education);
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				switch (i) {
				case 0:
					student.setSchoolStuNo((String)prop);
					break;
				case 1:
					student.setRealname((String)prop);
					break;
				case 2:
					student.setGender(prop+"");
					break;
				case 3:
					// 手机
					student.setTel(prop + "");
					break;
				default:
					break;
				}
			}
			student.setStuNo(channelId+"_"+student.getSchoolStuNo());
			students.add(student);
		}
		// 调用业务逻辑层代码完成批量保存操作
		studentService.batchInsertTrainStudent(students,trainId);
		return MessageUtil.success("导入成功");
	}
	public void inputStreamToFile(java.io.InputStream ins, File file) {
		try {
			java.io.OutputStream os = new java.io.FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
